package com.alageek.personalblog.handler;

import com.alageek.personalblog.common.constant.BlogConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理机制
 * @author AlaGeek
 */
@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {

    /**
     * 异常处理
     * @param e       异常对象
     * @param request 请求对象
     * @return 返回错误页面
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView resolveException(Exception e, HttpServletRequest request) throws Exception {
        log.debug("Request URL: {}, Exception: {}", request.getRequestURL(), e.getMessage());
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        String viewName = "error/error";
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject(BlogConstant.ATTR_NAME_URL, request.getRequestURL());
        modelAndView.addObject(BlogConstant.ATTR_NAME_EXCEPTION, e);
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

}
